package cc.ipost.ipost;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cc.ipost.ipost.data.RequestData;
import cc.ipost.ipost.utils.AnimationFactory;
import cc.ipost.ipost.utils.AnimationFactory.FlipDirection;
import cc.ipost.ipost.utils.ScreenShot;
import cc.ipost.ipost.utils.TuyaView;

import com.umeng.analytics.MobclickAgent;

@SuppressLint("HandlerLeak")
public class PostActivity extends Activity {
	View cover;
	View poster;
	ImageView coverPreview;
	Bitmap photoBm;
	Bitmap coverBm;
	TuyaView tuya = null;
	EditText coverText;
	ProgressDialog loadingDialog;
	EditText zipcodeT;
	EditText nameT;
	EditText addressT;
	String receiverId = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		this.setContentView(R.layout.post_main);
		initView();

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.cancel();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("get contacts info fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(PostActivity.this).setMessage(msgs)
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.ERR: {
				Log.e("post err", msg.toString());
				new AlertDialog.Builder(PostActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.i("post success", msg.toString());
				Intent i = new Intent(PostActivity.this, MainActivity.class);
				startActivity(i);
				System.out.println(msg.obj);
			}
			}

		}
	};

	private void toggleCameraBtnVisible() {
		View btn = cover.findViewById(R.id.cover_add_btn);
		if (btn.getVisibility() == View.VISIBLE) {
			btn.setVisibility(View.INVISIBLE);
		} else {
			btn.setVisibility(View.VISIBLE);
		}
	}
	
	private void back2home() {
				new AlertDialog.Builder(PostActivity.this)
						.setMessage(PostActivity.this.getString(R.string.post_cancel_warn))
						.setNegativeButton(PostActivity.this.getString(R.string.cancel), null)
						.setPositiveButton(PostActivity.this.getString(R.string.ok), new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								Intent in = new Intent(PostActivity.this, MainActivity.class);
								PostActivity.this.startActivity(in);
							}
						})
						.setCancelable(true)
						.show();
	}

	private void initView() {
		loadingDialog = new ProgressDialog(this);
		loadingDialog
				.setMessage("Please waiting for generatiing and uploading...");
		LayoutInflater li = LayoutInflater.from(this);
		final ViewFlipper vf = (ViewFlipper) this.findViewById(R.id.postcard);

		this.cover = li.inflate(R.layout.cover, null);
		this.poster = li.inflate(R.layout.poster, null);
		this.coverPreview = (ImageView) this.cover
				.findViewById(R.id.cover_preview);

		vf.addView(this.cover);
		vf.addView(this.poster);
		View btn = this.findViewById(R.id.navturn_btn);
		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				AnimationFactory.flipTransition(vf, FlipDirection.LEFT_RIGHT);
			}
		});
		View hbtn = this.findViewById(R.id.navhome_btn);
		hbtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				back2home();
			}
		});

		coverPreview.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				toggleCameraBtnVisible();
			}
		});

		// --- begin with tuya part

		tuya = new TuyaView(this, 380, 478);
		ImageView tuyaPreview = (ImageView) this.cover
				.findViewById(R.id.tuya_preview);
		tuya.setPreview(tuyaPreview);
		RelativeLayout tuyap = new RelativeLayout(this);
		tuyap.addView(tuya);
		View ud = new View(this);
		ud.setBackgroundResource(R.drawable.undo_icon);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(50, 54);
		ud.setLayoutParams(lp);
		tuyap.addView(ud);

		ud.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				tuya.undo();
			}
		});

		final PopupWindow pw = new PopupWindow(tuyap, 380, 478, true);
		final View rv = this.getWindow().getDecorView()
				.findViewById(android.R.id.content);
		pw.setBackgroundDrawable(new BitmapDrawable());

		View drawErea = this.cover.findViewById(R.id.draw_area);
		drawErea.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				pw.showAtLocation(rv, Gravity.CENTER, 0, 0);
			}
		});
		// --- end of tuya part

		// --- begin with edit text part

		coverText = (EditText) cover.findViewById(R.id.cover_text_edit);
		View editIcon = this.cover.findViewById(R.id.editareaicon);
		editIcon.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				coverText.setEnabled(true);
			}
		});
		final int num = 72;
		coverText.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				temp = s;
				System.out.println("s=" + s);
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void afterTextChanged(Editable s) {
				System.out.println("Len: " + s.length());
				selectionStart = coverText.getSelectionStart();
				selectionEnd = coverText.getSelectionEnd();
				// System.out.println("start="+selectionStart+",end="+selectionEnd);
				if (temp.length() > num) {
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionEnd;
					coverText.setText(s);
					coverText.setSelection(tempSelection);// 设置光标在最后
				}

			}
		});
		// --- end of text part

		View cameraBtn = this.cover.findViewById(R.id.camera_btn);
		cameraBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				/*
				 * String path=v.getContext().getFilesDir().getPath(); File
				 * file=new File(path); Intent it = new
				 * Intent(Intent.ACTION_VIEW); // Uri mUri =
				 * Uri.parse(fileName); Uri mUri =
				 * Uri.parse("file://"+file.getPath()); it.setDataAndType(mUri,
				 * "image/*"); startActivity(it);
				 */
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				intent.putExtra("noFaceDetection", true);
				intent.putExtra("return-data", false);
				// intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
				// intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());
				intent.putExtra("crop", "true");
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 1122);
				intent.putExtra("outputY", 1122);
				startActivityForResult(intent, 0);
			}
		});

		// --- begin with poster back
		View sendBtn = this.poster.findViewById(R.id.send_btn);
		View plusBtn = this.poster.findViewById(R.id.plus_btn);
		zipcodeT = (EditText) this.poster.findViewById(R.id.poster_zipcode);
		nameT = (EditText) this.poster.findViewById(R.id.poster_fname);
		addressT = (EditText) this.poster.findViewById(R.id.poster_address);
		plusBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(PostActivity.this,
						AddressListActivity.class);
				i.putExtra("forResult", true);
				startActivityForResult(i, 10);
			}
		});
		sendBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				loadingDialog.show();
				String filep = createCover();
				String text = coverText.getText().toString();
				String zip = zipcodeT.getText().toString();
				String name = nameT.getText().toString();
				String address = addressT.getText().toString();
				MyApplication ma = (MyApplication) getApplication();
				RequestData rd = new RequestData(String.format(
						MySettings.UCARD, ma.user.ID), RequestData.POST);
				if (receiverId != null) {
					rd.addParam("receiver", receiverId);
				} else {
					rd.addParam("zipcode", zip);
					rd.addParam("location", address);
					rd.addParam("fname", name);
					rd.addParam("lname", "");
				}
				rd.addParam("text", text);
				rd.setFile("cover", filep);
				WebServiceTask wst = new WebServiceTask(rd, handler);
				wst.execute("");
			}
		});
		// --- end of poster back

	}

	private String createCover() {

		/**
		 * TextView tv = new TextView(this); tv.setDrawingCacheEnabled(true);
		 * tv.setText(coverText); tv.layout(0, 0, 380, 478); tv.setTextSize(40);
		 * tv.setTextColor(Color.BLACK); tv.buildDrawingCache(); Bitmap textmap
		 * = tv.getDrawingCache();
		 **/

		coverBm = Bitmap.createBitmap(MySettings.COVERW, MySettings.COVERH,
				Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(coverBm);
		c.drawARGB(255, 255, 255, 255);
		if (photoBm != null) {
			c.drawBitmap(photoBm, 120, 75, null);
		}
		c.drawBitmap(tuya.getResult(), 1302, 75, null);
		// c.drawBitmap(textmap, 1302, 725, null);

		TextPaint tp = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
		tp.setColor(Color.BLACK);
		tp.setTextSize(60);
		// tp.setShadowLayer(5, 2, 2, Color.CYAN);
		Log.i("cerate cover", tp.toString());
		Log.i("cerate cover", "text: " + coverText.getText().toString());
		StaticLayout sl = new StaticLayout(coverText.getText().toString(), tp,
				380, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false);

		c.save();
		c.translate(1302, 725); // position text on the canvas
		sl.draw(c);
		c.restore();

		/*String fileUrl = Environment.getExternalStorageDirectory().toString()
				+ "/testcover.jpg";
				*/
		String fileUrl = this.getCacheDir().toString() + "/cover.jpg";
		try {
			FileOutputStream fos = new FileOutputStream(new File(fileUrl));
			coverBm.compress(CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
			return fileUrl;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileUrl;

	}

	protected Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	protected File getTempFile() {
		// if (Environment.getExternalStorageState().equals(
		// Environment.MEDIA_MOUNTED)) {
		// String imgpath = "diy.jpg";
		// String infoPath = Environment.getDownloadCacheDirectory() + imgpath;
		// File f = new File(infoPath);
		// try {
		// f.createNewFile();
		// } catch (IOException e) {
		// Toast.makeText(this, "SD临时文件读取错误！", Toast.LENGTH_LONG).show();
		// }
		// return f;
		// } else {
		File f = new File(getCacheDir(), "diy_" + ".jpg");
		try {
			f.createNewFile();
		} catch (IOException e) {
			Toast.makeText(this, "缓存目录临时文件读取错误！", Toast.LENGTH_LONG).show();
		}
		return f;
		// }
	}

	/*
	private void doCrop(Bitmap bp) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 612);
		intent.putExtra("outputY", 612);
		intent.putExtra("data", bp);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 1);
	}
	*/

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// super.onActivityResult(requestCode, resultCode, data);
		System.out.println("resultCode: " + resultCode);
		System.out.println("requestCode: " + requestCode);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 0:
				// Bitmap cp = (Bitmap) data.getExtras().get("data");
				// System.out.println(cp.getHeight());
				// Uri uri = data.getData();
				String action = data.getAction();
				if (action != null) {
					Uri uri = Uri.parse(action);
					Cursor cursor = getContentResolver().query(uri, null, null,
							null, null);
					cursor.moveToFirst();
					/*
					String imgNo = cursor.getString(0); // 图片编号
					String imgSize = cursor.getString(2); // 图片大小
					String imgName = cursor.getString(3); // 图片文件名
					*/
					String imgPath = cursor.getString(1); // 图片文件路径
					System.out.println(imgPath);
					try {
						Bitmap bitmap = MediaStore.Images.Media.getBitmap(
								this.getContentResolver(), uri);
						System.out.println(bitmap.getHeight());
						this.coverPreview.setImageBitmap(bitmap);
						photoBm = bitmap;
						toggleCameraBtnVisible();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// doCrop(cp);
				break;
			case 1:
				Bitmap bp = (Bitmap) data.getExtras().get("data");
				System.out.println(bp.getHeight());
				break;

			case 10: {
				Bundle info = data.getExtras();
				if (info != null) {
					nameT.setText(info.getString("name"));
					zipcodeT.setText(info.getString("zipcode"));
					addressT.setText(info.getString("location"));
					receiverId = info.getString("id");
				} else {
					Log.e("PostActivity", "onResult from contact list null");
				}
			}
				break;
			default:
				break;
			}

		}
		// Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
		// System.out.println(cameraBitmap.getHeight());
		super.onActivityResult(requestCode, resultCode, data);

	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			ScreenShot.shoot(this);

		}else if (keyCode == KeyEvent.KEYCODE_BACK) {
			back2home();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
